#!/usr/bin/env bun

/**
 * n8n 节点数据库维护脚本
 * 
 * 从 n8n API 获取所有节点类型信息并更新到 SQLite 数据库中
 */

import { Command } from 'commander';
import { N8NClient } from '../src/tools/n8n/client.js';
import { n8nNodeDb } from '../src/services/n8n-node-db.js';

const program = new Command();

program
  .name('maintain-n8n-nodes-db')
  .description('维护 n8n 节点数据库')
  .version('1.0.0');

// 更新节点数据命令
program
  .command('update')
  .description('从 n8n API 获取并更新节点数据')
  .option('--clear', '更新前清空现有数据')
  .option('--dry-run', '预览模式，不实际更新数据库')
  .action(async (options) => {
    console.log('🚀 开始更新 n8n 节点数据库...');
    const startTime = Date.now();

    try {
      // 初始化 n8n 客户端
      const client = new N8NClient();
      
      if (options.clear && !options.dryRun) {
        console.log('🗑️ 清空现有数据...');
        const deleted = await n8nNodeDb.clearAllNodes();
        console.log(`✅ 已删除 ${deleted} 个节点`);
      }

      console.log('🌐 从 n8n API 获取节点类型...');
      const nodeTypes = await client.getNodeTypes();
      console.log(`📋 获取到 ${nodeTypes.length} 个节点类型`);

      if (options.dryRun) {
        console.log('\\n🔍 预览模式 - 前 10 个节点:');
        nodeTypes.slice(0, 10).forEach((node, index) => {
          console.log(`  ${index + 1}. ${node.displayName || node.name} (${node.name})`);
          if (node.description) {
            console.log(`     📝 ${node.description.substring(0, 100)}...`);
          }
        });
        console.log(`\\n... 还有 ${nodeTypes.length - 10} 个节点`);
        return;
      }

      console.log('💾 更新数据库...');
      const result = await n8nNodeDb.upsertNodes(
      nodeTypes.map(node => ({
        name: node.name,
        displayName: node.displayName,
        description: node.description || undefined,
        version: node.version,
        group: (node as any).group || [],
        category: (node as any).category || undefined,
        subtitle: (node as any).subtitle || undefined,
        fullConfig: node
      }))
      );

      const duration = Date.now() - startTime;
      console.log(`\\n✅ 数据库更新完成!`);
      console.log(`📊 创建: ${result.created} 个节点`);
      console.log(`🔄 更新: ${result.updated} 个节点`);
      console.log(`⏱️ 耗时: ${duration}ms`);

      // 显示统计信息
      const stats = await n8nNodeDb.getStats();
      console.log(`\\n📈 数据库统计:`);
      console.log(`   总节点数: ${stats.totalNodes}`);
      console.log(`   分类数量: ${stats.categories}`);
      console.log(`   最后更新: ${stats.lastUpdated?.toLocaleString() || '未知'}`);

    } catch (error) {
      console.error('❌ 更新失败:', error);
      process.exit(1);
    } finally {
      await n8nNodeDb.disconnect();
    }
  });

// 查询数据库命令
program
  .command('query <keyword>')
  .description('搜索节点')
  .option('-c, --category <category>', '按类别过滤')
  .option('-g, --group <group>', '按分组过滤')
  .option('-l, --limit <number>', '限制结果数量', '10')
  .action(async (keyword, options) => {
    try {
      console.log(`🔍 搜索关键词: "${keyword}"`);
      
      const result = await n8nNodeDb.searchNodes({
        query: keyword,
        category: options.category,
        group: options.group,
        limit: parseInt(options.limit)
      });

      console.log(`\\n📋 找到 ${result.total} 个节点 (显示前 ${result.nodes.length} 个):`);
      result.nodes.forEach((node, index) => {
        console.log(`\\n  ${index + 1}. ${node.displayName} (${node.name})`);
        if (node.description) {
          console.log(`     📝 ${node.description.substring(0, 100)}...`);
        }
        if (node.category) {
          console.log(`     🏷️ 类别: ${node.category}`);
        }
        if (node.group.length > 0) {
          console.log(`     📦 分组: ${node.group.join(', ')}`);
        }
      });

    } catch (error) {
      console.error('❌ 查询失败:', error);
      process.exit(1);
    } finally {
      await n8nNodeDb.disconnect();
    }
  });

/**
 * 从节点信息中提取类别
 */
function extractCategory(node: any): string | null {
  // 优先使用 category 字段
  if (node.category) {
    return node.category;
  }
  
  // 从 group 中推断类别
  if (node.group && node.group.length > 0) {
    return node.group[0];
  }
  
  // 从名称推断类别
  const name = node.name.toLowerCase();
  if (name.includes('http') || name.includes('webhook')) {
    return 'communication';
  }
  if (name.includes('email') || name.includes('slack') || name.includes('discord')) {
    return 'communication';
  }
  if (name.includes('database') || name.includes('mysql') || name.includes('postgres')) {
    return 'database';
  }
  if (name.includes('aws') || name.includes('google') || name.includes('azure')) {
    return 'cloud';
  }
  
  return 'other';
}

program.parse();
